import { HomeAPI } from "@/api/HomeAPI";
import { CategoryAPI } from "@/api/CategoryAPI";
import type { Banner } from "@/types/Banner";
import type { Category } from "@/types/Category";
import type { Status } from "@/types/Status";
import { defineStore } from "pinia";
import type { Pagination } from "@/types/Response";
import type { Goods, GoodsRequestParams } from "@/types/Goods";

// 该 store 用于存储分类状态
type States = {
  categories: {
    // 用于存储导航分类数据
    headerNav: (Category & { isOpen: boolean })[];
    // 用于保存首页左侧分类数据
    homeCategory: Category[];
    // 用于跟踪请求状态
    status: Status;
  };
  // 轮播图状态
  banner: {
    result: Banner[];
    status: Status;
  };
  // 一级分类具体信息
  topCategories: {
    result: {
      [id: string]: Category;
    };
    status: Status;
  }
  // 二级分类筛选条件
  subCategoryFilters: {
    result: {
      [id: string]: Category;
    };
    status: Status;
  }
  // 二级分类商品
  categoryGoods: {
    status: Status;
    result: Pagination<Goods>;
  }
};
type Getters = {
  // 根据一级分类id获取一级分类对象
  currentTop: (
    state: States
  ) => (topCategoryId: string) => Category | undefined;
  currentTopAndSub: (
    state: States
  ) => (
      topCategoryId: string,
      subCategoryId: string
    ) => { topCategory: Category | undefined; subCategory: Category | undefined };
};
type Actions = {
  // 用于获取分类数据并保存分类数据的方法
  getCategories(): Promise<void>;
  toggle(id: string, target: boolean): void;
  // 获取轮播图数据并保存轮播图数据
  getBanners(distributionSite?: 1 | 2): Promise<void>;
  // 根据一级分类 id 获取分类信息
  getTopCategoryById(id: string): Promise<void>;
  // 根据二级分类 id 获取该分类下的商品的筛选条件
  getSubCategoryFilters(id: string): Promise<void>;
  // 获取二级分类商品
  getCategoryGoods(
    categoryId: GoodsRequestParams["categoryId"],
    reqParams?: Partial<Omit<GoodsRequestParams, "categoryId">>
  ): Promise<void>;
};

export const useCategoryStore = defineStore<
  "category",
  States,
  Getters,
  Actions
>("category", {
  state: () => ({
    // 分类状态
    categories: { headerNav: [], homeCategory: [], status: "idle" },
    // 轮播图状态
    banner: { result: [], status: "idle" },
    // 一级分类信息
    topCategories: {
      result: {},
      status: "idle",
    },
    // 二级分类筛选条件
    subCategoryFilters: {
      result: {},
      status: "idle",
    },
    // 二级分类商品
    categoryGoods: {
      result: {
        page: 0,
        pages: 0,
        pageSize: 0,
        counts: 0,
        items: [],
      },
      status: "idle"
    },
  }),
  getters: {
    // 根据一级分类id获取一级分类对象
    currentTop: (state) => {
      return function (topCategoryId) {
        return state.categories.headerNav.find(
          (item) => item.id === topCategoryId
        );
      };
    },
    currentTopAndSub: (state) => (topCategoryId, subCategoryId) => {
      // 先找一级分类对象
      const topCategory = state.categories.headerNav.find(
        (category) => category.id === topCategoryId
      );
      // 再找二级分类对象
      const subCategory = topCategory?.children?.find(
        (category) => category.id === subCategoryId
      );
      return { topCategory, subCategory };
    },
  },
  actions: {
    // 获取分类数据
    async getCategories() {
      // 更新请求状态
      this.categories.status = "loading";
      // 捕获错误
      try {
        // 发送请求获取分类数据
        const response = await CategoryAPI.getCategories();
        // 存储分类数据
        this.categories.headerNav = response.result.map((category) => ({
          ...category,
          isOpen: false,
        }));
        // 存储首页左侧分类数据
        this.categories.homeCategory = response.result.map((category) => ({
          ...category,
          children: category.children?.slice(0, 2),
        }));
        // 更新请求状态
        this.categories.status = "success";
      } catch (error) {
        // 更新请求状态
        this.categories.status = "error";
      }
    },
    // 修改一级分类对象中的 isOpen 属性的值
    toggle(id, target) {
      this.categories.headerNav = this.categories.headerNav.map((category) =>
        category.id === id ? { ...category, isOpen: target } : category
      );
    },
    // 获取轮播图数据并保存轮播图数据
    async getBanners(distributionSite = 2) {
      // 更新加载状态
      this.banner.status = "loading";
      // 捕获错误
      try {
        // 发送请求获取轮播图数据
        const response = await HomeAPI.getBanners(distributionSite);
        // 保存轮播图数据
        this.banner.result = response.result;
        // 更新加载状态
        this.banner.status = "success";
      } catch (error) {
        // 更新加载状态
        this.banner.status = "error";
      }
    },
    // 根据一级分类 id 获取分类信息
    async getTopCategoryById(id) {
      // 更新加载状态
      this.topCategories.status = "loading";
      // 捕获错误
      try {
        // 发送请求根据一级分类 id 获取分类信息
        const response = await CategoryAPI.getTopCategoryById(id);
        // 存储一级分类信息
        this.topCategories.result[response.result.id] = response.result;
        // 更新加载状态
        this.topCategories.status = "success";
      } catch (error) {
        // 更新加载状态
        this.topCategories.status = "error";
      }
    },
    // 根据二级分类 id 获取该分类下的商品的筛选条件
    async getSubCategoryFilters(id) {
      // 更新加载状态
      this.subCategoryFilters.status = "loading";
      // 捕获错误
      try {
        // 发送请求
        const response = await CategoryAPI.getSubCategoryFilters(id);
        // 存储筛选条件
        this.subCategoryFilters.result[response.result.id] = response.result;
        // 更新加载状态
        this.subCategoryFilters.status = "success"
      } catch (error) {
        // 更新加载状态
        this.subCategoryFilters.status = "error";
      }
    },
    // 获取二级分类商品
    async getCategoryGoods(categoryId, reqParams) {
      // 判断status 是否 为 finished 阻止程序继续执行
      if (this.categoryGoods.status === "finished") return;
      // 更新加载状态
      this.categoryGoods.status = "loading";
      // 捕获错误
      try {
        // 发送请求获取二级分类商品数据
        const response = await CategoryAPI.getCategoryGoods(
          categoryId,
          reqParams
        );
        // 判断当前请求的是否是第一页数据
        if (reqParams?.page === 1) {
          // 如果是  直接保存  
          // 存储二级分类商品数据
          this.categoryGoods.result = response.result;
        } else {
          // 如果不是 累加 保存商品列表
          this.categoryGoods.result = {
            ...response.result,
            items: [
              ...this.categoryGoods.result.items,
              ...response.result.items,
            ]
          }
        }
        // 判断用户当前访问的是不是最后一页
        if (reqParams?.page === response.result.pages ||
          // 判断是否是只有一页数据
          response.result.pages === 0) {
          // 把状态更改为 finished 标识没有更多数据可以加载
          this.categoryGoods.status = "finished"
        } else {
          // 更新加载状态
          this.categoryGoods.status = "success";
        }
      } catch (error) {
        // 更新加载状态
        this.categoryGoods.status = "error"
      }
    }
  },
});
